﻿/* 
 * This file is part of the Coffee Survey Framework - http://coffee.codeplex.com
 */
using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;

namespace Coffee
{
    public class SQLClient
    {
        public static DataSet ExecStoredProc(XmlNode node)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = node.SelectSingleNode("name/text()").Value;
            cmd.CommandType = CommandType.StoredProcedure;
            XmlNodeList xParams = node.SelectNodes("params/param");
            if ((xParams != null) && (xParams.Count > 0))
            {
                foreach (XmlNode xParam in xParams)
                {
                    cmd.Parameters.Add(CreateParameter(xParam));
                }
            }
            return FetchHandler(cmd);
        }

        public static SqlParameter CreateParameter(XmlNode node)
        {
            string name = node.SelectSingleNode("name/text()").Value;
            string type = node.SelectSingleNode("type/text()").Value;
            DbType dbtype = (DbType)Enum.Parse(typeof(DbType), type);
            SqlParameter nParam = new SqlParameter("@" + name, dbtype);
            nParam.Value = Parser.ParseValue(node.SelectSingleNode("value"));
            return nParam;
        }

        public static ExecuteFetchHandler FetchHandler;
        public delegate DataSet ExecuteFetchHandler(SqlCommand cmd);
    }
}
